package scau.gsmg.misp.dao.impl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.shiro.authc.UnknownAccountException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import scau.gsmg.misp.dao.BaseDAO;
import scau.gsmg.misp.dao.IUserDAO;
import scau.gsmg.misp.utils.IncorrectCaptchaException;
import scau.gsmg.misp.vo.Role;
import scau.gsmg.misp.vo.User;
import scau.gsmg.misp.vo.UserRole;

@Repository
public class UserDAO extends BaseDAO implements IUserDAO {

	/**
	 * 得到所有的用户信息，并且分页
	 */
	@Override
	public List getAllUser(String page, String rows, String sort, String order)
			throws Exception {
		// TODO Auto-generated method stub
		String name = null;
		List dataList = new ArrayList();
		String hql1 = "from UserRole u";
		// System.out.println("DAO" + "sort" + sort + "order" + order);
		dataList = searchAllUser(hql1, name, page, rows);
		return dataList;
	}

	/**
	 * @Description:分页的实现
	 */
	private List searchAllUser(String hql, String name, String page, String rows) {
		Session session = getSession();
		List dataList = new ArrayList();
		try {
			// 当为缺省值的时候进行赋值
			int currentpage = Integer
					.parseInt((page == null || page == "0") ? "1" : page);// 第几页
			int pagesize = Integer
					.parseInt((rows == null || rows == "0") ? "10" : rows);// 每页多少行
			Query query = session.createQuery(hql);
			if (name != null) {
				query.setParameter(0, "%" + name + "%");
			}
			List<UserRole> userRole = query
					.setFirstResult((currentpage - 1) * pagesize)
					.setMaxResults(pagesize).list();
			// 估计是分页出错
			for (UserRole u : userRole) {
				HashMap<String, Object> jsonMap = new HashMap<String, Object>();
				jsonMap.put("id", u.getId());
				jsonMap.put("user.name", u.getUser().getName());
				jsonMap.put("roleName", u.getRole().getName());
				jsonMap.put("roleId", u.getRole().getId());
				jsonMap.put("user.gender", u.getUser().getGender());
				jsonMap.put("user.birthday", u.getUser().getBirthday()
						.toString());
				jsonMap.put("user.email", u.getUser().getEmail());
				jsonMap.put("user.cellphone", u.getUser().getCellphone());
				jsonMap.put("createTime", u.getUser().getCreateTime()
						.toString());
				jsonMap.put("count", u.getUser().getCount());
				jsonMap.put("lastVisit", u.getUser().getLastVisit());
				dataList.add(jsonMap);
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("捕获异常：" + e);
		} finally {
			session.close();
		}
		return dataList;
	}

	/**
	 * 统计一共有多少行数据
	 */
	@Override
	public int getUserCount() throws Exception {
		// TODO Auto-generated method stub
		int count = 0;
		String hql = "from UserRole u";
		count = count(hql);
		return count;
	}

	/**
	 * @Description:count 方法统计数量
	 */
	private int count(String hql) throws Exception {
		Session session = getSession();
		int size = 0;
		try {
			Query query = session.createQuery(hql);
			List list = query.list();
			size = list.size();

		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("捕获异常：" + e);
		} finally {
			session.close();
		}
		return size;
	}

	/**
	 * @Description:获取role角色(combobox)
	 */
	@Override
	public List userCombobox() throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		String hql = "from Role r";
		List<HashMap<String, Object>> dataList = new ArrayList();
		try {
			Query query = session.createQuery(hql);
			List<Role> role = query.list();
			for (Role r : role) {
				HashMap<String, Object> jsonMap = new HashMap<String, Object>();
				jsonMap.put("id", r.getId());
				jsonMap.put("text", r.getName());
				dataList.add(jsonMap);
			}
			return dataList;
		} catch (Exception e) {
			System.out.println("userCombobox " + e);
		} finally {
			session.close();
		}
		return null;
	}

	/**
	 * @Description:增加用户
	 */
	@Override
	public boolean addUser(User user, int roleId) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		// 插入当前时间
		Date date = new Date();
		String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(date);// 将时间格式转换成符合Timestamp要求的格式
		Timestamp time = Timestamp.valueOf(nowTime);
		/*
		 * System.out.println(user.getId() + user.getName() +
		 * user.getCellphone() + user.getEmail() + user.getGender() + time);
		 */
		try {
			user.setCreateTime(time);
			user.setPassword("123");
			user.setCount(0);
			session.save(user);
			Role role = new Role();
			role.setId(roleId);
			UserRole userRole = new UserRole();
			userRole.setRole(role);
			userRole.setUser(user);
			session.save(userRole);
			tx.commit();
			return true;
		} catch (Exception e) {
			System.out.println("adduser" + e);
			return false;
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
	}

	/**
	 * @Description:删除用户UserRole
	 */
	@Override
	public boolean removeUser(int id) throws Exception {
		// TODO Auto-generated method stub
		boolean flag = false;
		Session session = getSession();
		try {

			String hql1 = "from UserRole where id=" + id;
			Query query1 = session.createQuery(hql1);
			List<UserRole> userRoles = query1.list();
			String hql = "delete UserRole g where g.id=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, id);
			query.executeUpdate();
			for (UserRole u : userRoles) {
				flag = userId(u.getUser().getId());
			}
			flag = true && flag;
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		} finally {
			session.close();
		}
		return flag;
	}

	/**
	 * @Description:根据UId,删除用户User
	 */
	private boolean userId(int id) {
		Session session = getSession();
		try {

			String hql = "delete User g where g.id=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, id);
			query.executeUpdate();
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		} finally {
			session.close();
		}
		return true;
	}

	/**
	 * @Description:修改用户
	 */
	@Override
	public boolean editUser(int id, int roleId, User user) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		try {

			int uid = searchUid(id);
			String hql = "update User u set u.name=?,u.gender=?,u.cellphone=?, u.email=?,u.birthday=? where u.id=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, user.getName());
			query.setParameter(1, user.getGender());
			query.setParameter(2, user.getCellphone());
			query.setParameter(3, user.getEmail());
			query.setParameter(4, user.getBirthday());
			query.setParameter(5, uid);
			query.executeUpdate();

			String hql1 = "update UserRole u set u.role.id=? where u.id=?";
			Query query1 = session.createQuery(hql1);
			query1.setParameter(0, roleId);
			query1.setParameter(1, id);
			query1.executeUpdate();
			tx.commit();
			return true;
		} catch (Exception e) {
			System.out.println("捕获异常：ww" + e);
			return false;
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
	}

	/**
	 * @Description:从UserRole获取User
	 */
	private int searchUid(int id) {
		Session session = getSession();
		// Transaction tx = session.beginTransaction();
		try {
			String hql1 = "from UserRole where id=" + id;
			Query query1 = session.createQuery(hql1);
			List<UserRole> userRoles = query1.list();
			for (UserRole u : userRoles) {
				return u.getUser().getId();
			}
		} catch (Exception e) {
			System.out.println("捕获异常：ww" + e);
			// return 0;
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return 0;
	}

	/*
	 * @Description:搜索用户
	 */
	@Override
	public List searchUser(String page, String rows, int id, String name,
			String sort, String order) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		String param = null;
		String hql = "from UserRole u";
		List dataList = new ArrayList();
		try {
			if (id != 0) {
				hql = "from UserRole u where u.id=" + id;

			}
			if (name != null) {
				hql = "from UserRole u where u.user.name like ?";
				dataList = searchAllUser(hql, name, page, rows);
				return dataList;
			}
			dataList = searchAllUser(hql, param, page, rows);
		} catch (Exception e) {
			System.out.println("捕获异常：ww" + e);
			// return 0;
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}

		return dataList;
	}

	/*
	 * @Description:搜索用户数量
	 */
	@Override
	public int searchCount(int id, String name) throws Exception {
		// TODO Auto-generated method stub
		String hql = "";
		Session session = getSession();
		hql = "from UserRole";
		try {
			if (id != 0) {
				hql = "from UserRole u where u.id=" + id;

			}
			if (name != null) {
				hql = "from UserRole u where u.user.name like ?";
				Query query = session.createQuery(hql);
				query.setParameter(0, "%" + name + "%");
				return query.list().size();
			}

			Query query = session.createQuery(hql);
			return query.list().size();
		} catch (Exception e) {
			System.out.println("捕获异常：ww" + e);
			// return 0;
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return 0;

	}

	@Override
	public User userLogin(String name) {
		// TODO Auto-generated method stub
		String hql = "";
		Session session = getSession();
		// hql = "from User where name=? and password=?";
		hql = "from User where name=?";
		Query query = session.createQuery(hql);
		System.out.println(name);
		query.setParameter(0, name);
		// query.setParameter(0,user.getPassword());
		List<User> list = query.list();
		session.close();
		if (list.size() != 0) {
			System.out.println(list.size());
			return (User) list;
		}
		return null;
	}

	@Override
	public String ok(String name) {
		// TODO Auto-generated method stub
		return name + "@@";
	}

	@Override
	public void success(String name) {
		// TODO Auto-generated method stub
		String hql = "";
		Session session = getSession();
		// hql = "from User where name=? and password=?";
		hql = "from Member where name=?";
		Query query = session.createQuery(hql);
		System.out.println(name);
		query.setParameter(0, "111");
		// query.setParameter(0,user.getPassword());
		List<User> list = query.list();
		session.close();
		if (list.size() != 0) {
			System.out.println(list.size());
			// return ((User) list).getPassword();
		}
		// return null;
	}

	@Override
	public User login(User user) {

		String hql = "";
		Session session = getSession();
		User success=new User();
		success=null;
		hql = "from User where id=?";
		//try {
			Query query = session.createQuery(hql);
			System.out.println(user.getName() + user.getId());
			query.setParameter(0, user.getId());
			List<User> list = query.list();
			
			if (list.size() != 0) {
				System.out.println(list.size());
				success=list.get(0);
				for(UserRole ur:success.getUserRoles()){
					System.out.println(ur.getRole().getRoleCode()+"  "+ur.getRole().getName()+"   "+ur.getId());
				}
				
			}else{
				throw new  UnknownAccountException();
			}
			System.out.println("TTTTTTTT___TTTTTTT");
		/*} catch (Exception e) {
			System.out.println("捕获异常：ww" + e);
			// return 0;
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}*/
		session.close();
		return success;

	}
}
